﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using Ext.Net;
using FastTravel.BusinessLogic;
using FastTravel.DB;
using FastTravel.DB.Enums;
using FastTravel.DB.Helpers;
using FastTravel.Utilites;
using ListItem = System.Web.UI.WebControls.ListItem;

namespace FastTravel.IntranetWeb
{
	/// <summary>
	/// Страница добавления клиента
	/// </summary>
	public partial class CustomerAdd : BasePage
	{
		/// <summary>
		/// Загрузка страницы
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void Page_Load(object sender, EventArgs e)
		{
			
			if (!ExtNet.IsAjaxRequest)
			{
				// Заполняем дроп-даун семейного положения клиента
				
				Type marritalType = typeof(MarritalStatus);
				Dictionary<int, string> statusList = EnumMetadataConverter.GetListItems(marritalType);

				var dropdawnList = new List<object>();

				foreach (var item in statusList)
				{
					dropdawnList.Add(new {Text = item.Value, Value = item.Key});
				}
				this.storeMarritialStatus.DataSource = dropdawnList;
				this.storeMarritialStatus.DataBind();
			}

			txtLastName.Focus();

		}

		/// <summary>
		/// Добавление нового клиента (показываем окно подтверждения)
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void BtnSaveClick(object sender, DirectEventArgs e)
		{
			
			if (!string.IsNullOrWhiteSpace(txtLastName.Text))
			{
				lblLastName.Text = txtLastName.Text;
				lblFirstName.Text = txtFirstName.Text;
				lblMiddleName.Text = txtMiddleName.Text;
				lblAddres1.Text = txtAddressLine1.Text;
				lblAddress2.Text = txtAddressLine2.Text;
				lblAuthority.Text = txtAuthority.Text;
				lblEmail.Text = txtEmail.Text;
				lblHomePhone.Text = txtHomePhone.Text;
				lblWorkPhone.Text = txtWorkPhone.Text;
				lblMobilePhone.Text = txtMobilePhone.Text;
				lblProfession.Text = txtProfession.Text;
				lblJob.Text = txtJobPlace.Text;
				lblMarritalStatus.Text = comboMarritialStatus.SelectedItem.Text;
				lblPassportNumber.Text = txtNumber.Text;


				if (timeEmptyExtControls.CompareWithoutSeconds(dateBirth.SelectedDate) != 0)
				{
					lbldateBirth.Text = dateBirth.SelectedDate.ToShortDateString();
				}

				if (timeEmptyExtControls.CompareWithoutSeconds(dateFieldFrom.SelectedDate) != 0)
				{
					lblDateFrom.Text = dateFieldFrom.SelectedDate.ToShortDateString();
				}

				if (timeEmptyExtControls.CompareWithoutSeconds(dateFieldTo.SelectedDate) != 0)
				{
					lblDateTo.Text = dateFieldTo.SelectedDate.ToShortDateString();
				}

				this.wndSaveConfirm.Show();
			}	

			txtLastName.Focus();
		}

		/// <summary>
		/// Подтверждение нового клиента
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void BtnSaveConfirm(object sender, DirectEventArgs e)
		{
			// Проверяем поля и создаем клиента
			string lastNameForSave = txtLastName.Text ?? string.Empty;
			string firstNameforSave = txtFirstName.Text ?? string.Empty;
			string middleNameForSave = txtMiddleName.Text ?? string.Empty;
			string address1ForSave = txtAddressLine1.Text ?? string.Empty;
			string address2ForSave = txtAddressLine2.Text ?? string.Empty;
			string jobForSave = txtJobPlace.Text ?? string.Empty;
			string professionForSave = txtProfession.Text ?? string.Empty;
			string emailForSave = txtEmail.Text ?? string.Empty;
			string authorityForSave = txtAuthority.Text ?? string.Empty;
			string passportNumberForSave = txtNumber.Text ?? string.Empty;

			MarritalStatus marritalForSave = EnumMetadataConverter.NumToEnum<MarritalStatus>(comboMarritialStatus.SelectedIndex);

			Int64 phoneWorkForSave = 0;
			if (!string.IsNullOrWhiteSpace(txtWorkPhone.Text))
			{
				phoneWorkForSave = Convert.ToInt64(txtWorkPhone.Text);
			}

			Int64 phoneHomeForSave = 0;
			if(!string.IsNullOrWhiteSpace(txtHomePhone.Text))
			{
				phoneHomeForSave = Convert.ToInt64(txtHomePhone.Text);
			}

			Int64 phoneMobileForSave = 0;
			if (!string.IsNullOrWhiteSpace(txtMobilePhone.Text))
			{
				phoneMobileForSave = Convert.ToInt64(txtMobilePhone.Text);
			}

			// если время не указано, устанавливаем его в MSSQL совместимое
			DateTime dateBirthForSave = dateBirth.SelectedDate;
			if (dateBirthForSave.CompareWithoutSeconds(timeEmptyExtControls) == 0)
			{
				dateBirthForSave = timeForMSSQLServer;
			}

			DateTime dateExpirityForSave = dateFieldFrom.SelectedDate;
			if (dateExpirityForSave.CompareWithoutSeconds(timeEmptyExtControls) == 0)
			{
				dateExpirityForSave= timeForMSSQLServer;
			}

			DateTime dateIssueForSave = dateFieldTo.SelectedDate;
			if (dateIssueForSave.CompareWithoutSeconds(timeEmptyExtControls) == 0)
			{
				dateIssueForSave = timeForMSSQLServer;
			}

			Customer newCustomer = CustomerManager.Add(firstNameforSave, lastNameForSave, middleNameForSave, phoneHomeForSave, phoneWorkForSave,
									phoneMobileForSave, professionForSave, jobForSave, marritalForSave, address1ForSave,
									address2ForSave, dateBirthForSave, emailForSave);
			
			BusinessLogicManager.Commit();

			// создаем паспорт клиента
			CustomerManager.AddPassport(newCustomer.ID, authorityForSave, dateExpirityForSave, dateIssueForSave, passportNumberForSave);

			BusinessLogicManager.Commit();

			ExtNet.Msg.Notify("Сообщение", "Новый клиент добавлен!").Show();
			
			// Очищаем поля
			txtAddressLine1.Clear();
			txtAddressLine2.Clear();
			txtAuthority.Clear();
			txtEmail.Clear();
			txtFirstName.Clear();
			txtHomePhone.Clear();
			txtJobPlace.Clear();
			txtLastName.Clear();
			txtMiddleName.Clear();
			txtMobilePhone.Clear();
			txtNumber.Clear();
			txtProfession.Clear();
			txtWorkPhone.Clear();
			dateBirth.Clear();
			dateFieldFrom.Clear();
			dateFieldTo.Clear();

			// Закрываем окно
			this.wndSaveConfirm.Hide();
		}

		/// <summary>
		/// Отмена подтверждения нового клиента
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void BtnCancelConfirm(object sender, DirectEventArgs e)
		{
			// Очищаем лэйблы в окне подтверждения
			lblAddres1.Text = string.Empty;
			lblAddress2.Text = string.Empty;
			lblAuthority.Text = string.Empty;
			lbldateBirth.Text = string.Empty;
			lblDateFrom.Text = string.Empty;
			lblDateTo.Text = string.Empty;
			lblEmail.Text = string.Empty;
			lblFirstName.Text = string.Empty;
			lblHomePhone.Text = string.Empty;
			lblJob.Text = string.Empty;
			lblLastName.Text = string.Empty;
			lblMarritalStatus.Text = string.Empty;
			lblMiddleName.Text = string.Empty;
			lblMobilePhone.Text = string.Empty;
			lblPassportNumber.Text = string.Empty;
			lblProfession.Text = string.Empty;
			lblWorkPhone.Text = string.Empty;

			this.wndSaveConfirm.Hide();
		}

	}
}